package com.zfzs.post.modules.flow.service.impl;

import com.zfzs.post.modules.flow.domain.OtherIncome;
import com.zfzs.post.modules.flow.repository.OtherIncomeRepository;
import com.zfzs.post.modules.flow.service.OtherIncomeService;
import com.zfzs.post.utils.DateStrUtils;
import com.zfzs.post.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author wq
 * @date 2019-10-21
 */
@Service
public class OtherIncomeServiceImpl implements OtherIncomeService {

    @Autowired
    private OtherIncomeRepository otherIncomeRepository;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public List<OtherIncome> findByAgentId(Long agentId) {
        return otherIncomeRepository.findByAgentId(agentId);
    }


    @Override
    public List<OtherIncome> findByAgentIdAndTime(Long agentId, String startDate, String endDate, Integer pageNum) {


        Sort sort = new Sort(Sort.Direction.DESC,"createTime");

        Pageable pageable = PageRequest.of(pageNum,10,sort);

        if(StringUtils.isEmpty(startDate) && StringUtils.isEmpty(endDate)){
            return otherIncomeRepository.findByAgentId(agentId,pageable);
        }else {
            Query query =new Query().skip(pageNum*10).limit(10);

            query.addCriteria(Criteria.where("createTime").gte(endDate).lte(startDate));
            query.addCriteria(Criteria.where("agentId").is(agentId));
            query.with(sort);
            List<OtherIncome> list = mongoTemplate.find(query, OtherIncome.class);
            return list;
        }
    }

    @Override
    public void save(OtherIncome otherIncome){
        otherIncome.setCreateTime(new Date());
        otherIncomeRepository.save(otherIncome);
    }

    @Override
    public OtherIncome findOneBySnAndTitle(Long agentId, String sn, String title) {
        Query query =new Query();

        query.addCriteria(Criteria.where("detailList").regex(sn));
        query.addCriteria(Criteria.where("title").regex(title));
        query.addCriteria(Criteria.where("agentId").is(agentId));
        OtherIncome one = mongoTemplate.findOne(query, OtherIncome.class);
        return one;
    }

}